﻿using System;
using System.Windows;
using System.Windows.Input;

namespace Red.Controls.Utils
{
    /// <summary>
    /// A Method of invoking the Custom Variable dialog.
    /// It also requires an associated <see cref="CustomVariableDialogCommand"/> instance specified as the command parameter
    /// </summary>
    /// <example>
    /// This is a continuation of the <see cref="CustomVariableDialogCommand"/> example
    /// <code>
    ///     <Button Text="Press me!" Command="{StaticResource CustomVariableDialogCommand}" CommandParameter="{StaticResource CustomVariableDialogCommand}" />
    /// </code>
    /// </example>
    public sealed class CustomVariableDialogCommand : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute( object parameter )
        {
            return true;
        }

        public void Execute( object parameter )
        {
            CustomVariableDialogCommandParam param = parameter as CustomVariableDialogCommandParam;

            CustomVariablePickerDialog dialog = new CustomVariablePickerDialog() { DataContext = param?.TargetTextBox, Owner = Window.GetWindow( param?.TargetTextBox as DependencyObject ) };
            dialog.ShowDialog();
        }
    }

    /// <summary>
    /// Contains all of the configuration parameters for <see cref="CustomVariableDialogCommand"/>
    /// </summary>
    /// <example>
    /// Where "TargetTextBox" is the <see cref="TextBox"/> (or compatible) control you'd like to see populated by this control
    /// <code><![CDATA[
    /// <ResourceDictionary>
    ///     <utils:CustomVariableDialogCommandParam x:Key="CustomVariableDialogCommandParam" TargetTextBox="{Binding}" />
    ///     <utils:CustomVariableDialogCommand x:Key="CustomVariableDialogCommand"/>
    /// </ResourceDictionary>]]>
    /// </code>
    /// </example>
    public sealed class CustomVariableDialogCommandParam : Freezable
    {
        // CustomVariableDialogCommandParam inherits from Freezable so that we inherit the DataContext of the parent:
        // http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
        protected override Freezable CreateInstanceCore()
        {
            return new CustomVariableDialogCommandParam();
        }

        public static readonly DependencyProperty TargetTextBoxProperty = DependencyProperty.Register( "TargetTextBox", typeof( object ), typeof( CustomVariableDialogCommandParam ) );

        public object TargetTextBox
        {
            get { return GetValue( TargetTextBoxProperty ); }
            set { SetValue( TargetTextBoxProperty, value ); }
        }
    }
}
